import { createI18n } from 'vue-i18n'

import { storage } from '@/utils/sessionStorage'

const supportedLanguages: Language[] = ['zh-CN', 'en-US']
function generateI18nMessages() {
  const messages: { [key in Language]?: Record<string, any> } = {}
  const modules = import.meta.glob(`./lang/**/*.json`, {
    eager: true,
    import: 'default'
  })
  console.log('modules: ', modules)
  //1. 遍历所有文件，获取语言代码，采用平铺的方式
  Object.keys(modules).forEach(key => {
    const moduleMessages = modules[key] as any
    const [lang, _] = key.replace('./lang/', '').replace('.json', '').split('/')
    console.log(_)
    if (!messages[lang]) {
      messages[lang] = {}
    }
    for (const key2 in moduleMessages) {
      messages[lang][key2] = moduleMessages[key2]
    }
  })
  // 2.处理的是en-US下有多文件层级的情况
  // function getMsg(obj, arr: string[]) {
  //   if (!arr.length) {
  //     return
  //   }
  //   const item = arr.shift()!
  //   console.log('item: ', item)
  //   let next = arr.length === 0 ? moduleMessages : {}
  //   if (obj[item]) {
  //     next = obj[item]
  //   }
  //   obj[item] = next
  //   getMsg(next, arr)
  // }
  // getMsg(messages, arr)
  console.log('messages: ', messages)
  return messages
}
const getCurrentLanguage = () => {
  //设置
  const navLang = navigator.language //系统语言
  console.log('navLang: ', navigator, navLang)
  const storageLang = storage.get('lang') //本地存储
  console.log('storageLang: ', storageLang)
  const localLang = navLang.indexOf('zh') !== -1 ? 'zh-CN' : 'en-US' || 'zh'
  let langCode = 'zh-CN'
  if (storageLang) {
    langCode = storageLang?.indexOf('zh') !== -1 ? 'zh-CN' : 'en-US'
  } else {
    langCode = localLang
  }
  storage.set('lang', langCode)
  return langCode
}

const i18n = createI18n({
  legacy: false, // 如果要支持compositionAPI，此项必须设置为false;
  // globalInjection: true, // 全局注册$t方法
  locale: getCurrentLanguage(),
  fallbackLocale: supportedLanguages[0],
  availableLocales: supportedLanguages,
  messages: generateI18nMessages()
})

export default i18n
